{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "from tensorflow.contrib.tensorboard.plugins import projector"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-2-a7be84dbebf1>:2: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From /Users/alan/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please write your own downloading logic.\n",
      "WARNING:tensorflow:From /Users/alan/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting MNIST_data/train-images-idx3-ubyte.gz\n",
      "WARNING:tensorflow:From /Users/alan/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting MNIST_data/train-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From /Users/alan/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.one_hot on tensors.\n",
      "Extracting MNIST_data/t10k-images-idx3-ubyte.gz\n",
      "Extracting MNIST_data/t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From /Users/alan/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From <ipython-input-2-a7be84dbebf1>:71: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "\n",
      "Future major versions of TensorFlow will allow gradients to flow\n",
      "into the labels input on backprop by default.\n",
      "\n",
      "See `tf.nn.softmax_cross_entropy_with_logits_v2`.\n",
      "\n",
      "Iter 0, Testing Accuracy = 0.1435\n",
      "Iter 300, Testing Accuracy = 0.9433\n",
      "Iter 600, Testing Accuracy = 0.9563\n",
      "Iter 900, Testing Accuracy = 0.9619\n",
      "Iter 1200, Testing Accuracy = 0.9645\n",
      "Iter 1500, Testing Accuracy = 0.9703\n",
      "Iter 1800, Testing Accuracy = 0.9711\n",
      "Iter 2100, Testing Accuracy = 0.9731\n",
      "Iter 2400, Testing Accuracy = 0.9704\n",
      "Iter 2700, Testing Accuracy = 0.9705\n",
      "Iter 3000, Testing Accuracy = 0.9741\n",
      "Iter 3300, Testing Accuracy = 0.9762\n",
      "Iter 3600, Testing Accuracy = 0.9782\n",
      "Iter 3900, Testing Accuracy = 0.9769\n",
      "Iter 4200, Testing Accuracy = 0.9737\n",
      "Iter 4500, Testing Accuracy = 0.9765\n",
      "Iter 4800, Testing Accuracy = 0.9784\n",
      "Iter 5100, Testing Accuracy = 0.9784\n",
      "Iter 5400, Testing Accuracy = 0.9793\n",
      "Iter 5700, Testing Accuracy = 0.9799\n",
      "Iter 6000, Testing Accuracy = 0.9783\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<bound method BaseSession.close of <tensorflow.python.client.session.Session object at 0xb261840f0>>"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#load dataset\n",
    "mnist = input_data.read_data_sets(\"MNIST_data\",one_hot=True)\n",
    "#number of cycles\n",
    "max_steps = 6001\n",
    "#number of pictures\n",
    "image_num = 3000\n",
    "#file directory\n",
    "DIR = \"/Users/alan/Documents/TensorflowProjects/\"\n",
    "\n",
    "#define session\n",
    "sess = tf.Session()\n",
    "\n",
    "#load pictures\n",
    "embedding = tf.Variable(tf.stack(mnist.test.images[:image_num]), trainable=False, name='embedding')\n",
    "\n",
    "#parameter summary\n",
    "def variable_summaries(var):\n",
    "    with tf.name_scope('summaries'):\n",
    "        mean = tf.reduce_mean(var)\n",
    "        tf.summary.scalar('mean',mean) \n",
    "        with tf.name_scope('stddev'):\n",
    "            stddev = tf.sqrt(tf.reduce_mean(tf.square(var-mean)))\n",
    "        tf.summary.scalar('stddev',stddev)\n",
    "        tf.summary.scalar('max',tf.reduce_max(var))\n",
    "        tf.summary.scalar('min',tf.reduce_min(var))\n",
    "        tf.summary.histogram('histogram',var)\n",
    "\n",
    "#name scope\n",
    "with tf.name_scope('input'):\n",
    "    #none here means the first dimention can be any number\n",
    "    x = tf.placeholder(tf.float32, [None,784],name='x-input')\n",
    "    #correct label\n",
    "    y = tf.placeholder(tf.float32, [None,10],name='y-input')\n",
    "\n",
    "#show images\n",
    "with tf.name_scope('input_reshape'):\n",
    "    image_shaped_input = tf.reshape(x, [-1,28,28,1])\n",
    "    tf.summary.image('input',image_shaped_input,10)\n",
    "\n",
    "with tf.name_scope('layer'):\n",
    "    #create a simple neuronet\n",
    "    with tf.name_scope('weights_1'):\n",
    "        W1 = tf.Variable(tf.truncated_normal([784,500],stddev=0.1),name='W1')\n",
    "        variable_summaries(W1)\n",
    "    with tf.name_scope('biases_1'):\n",
    "        b1 = tf.Variable(tf.zeros([500])+0.1,name='b1')\n",
    "        variable_summaries(b1)\n",
    "    with tf.name_scope('L1'):\n",
    "        L1 = tf.nn.tanh(tf.matmul(x,W1) + b1)\n",
    "    with tf.name_scope('weights_2'):\n",
    "        W2 = tf.Variable(tf.truncated_normal([500,300],stddev=0.1),name='W2')\n",
    "        variable_summaries(W2)\n",
    "    with tf.name_scope('biases_2'):\n",
    "        b2 = tf.Variable(tf.zeros([300])+0.1,name='b2')\n",
    "        variable_summaries(b2)\n",
    "    with tf.name_scope('L2'):\n",
    "        L2 = tf.nn.tanh(tf.matmul(L1,W2) + b2)\n",
    "    with tf.name_scope('weights_3'):\n",
    "        W3 = tf.Variable(tf.truncated_normal([300,10],stddev=0.1),name='W3')\n",
    "        variable_summaries(W3)\n",
    "    with tf.name_scope('biases_3'):\n",
    "        b3 = tf.Variable(tf.zeros([10])+0.1,name='b3')\n",
    "        variable_summaries(b3)\n",
    "    with tf.name_scope('L3'):\n",
    "        L3 = tf.nn.tanh(tf.matmul(L2,W3) + b3)\n",
    "    with tf.name_scope('softmax'):\n",
    "        prediction = tf.nn.softmax(L3)\n",
    "\n",
    "with tf.name_scope('loss'):\n",
    "    #cross entropy cost\n",
    "    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))\n",
    "    tf.summary.scalar('loss',loss)\n",
    "with tf.name_scope('train'):\n",
    "    #gradient descent\n",
    "    train_step = tf.train.AdamOptimizer(0.001).minimize(loss)\n",
    "\n",
    "#initialize variables\n",
    "sess.run(tf.global_variables_initializer())\n",
    "\n",
    "with tf.name_scope('accuracy'):\n",
    "    with tf.name_scope('correct_prediction'):\n",
    "        #result is stored in a boolean list\n",
    "        correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1)) #argmax returns the position of the greatest number in a list\n",
    "    with tf.name_scope('accuracy'):\n",
    "        #find accuracy\n",
    "        accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) #change correct_prediction into float 32 type\n",
    "        tf.summary.scalar('accuracy', accuracy)\n",
    "\n",
    "tf.gfile.MakeDirs(DIR + 'Homework5/projector')\n",
    "tf.gfile.MakeDirs(DIR + 'Homework5/data')\n",
    "        \n",
    "#create metadata file\n",
    "if tf.gfile.Exists(DIR + 'Homework5/projector/metadata.tsv'):\n",
    "    tf.gfile.DeleteRecursively(DIR + 'Homework5/projector')\n",
    "    tf.gfile.MkDir(DIR + 'Homework5/projector')\n",
    "with open(DIR + 'Homework5/projector/metadata.tsv', 'w')  as f:\n",
    "    labels = sess.run(tf.argmax(mnist.test.labels[:],1))\n",
    "    for i in range(image_num):\n",
    "        f.write(str(labels[i]) + '\\n')\n",
    "        \n",
    "#combine all summaries\n",
    "merged = tf.summary.merge_all()\n",
    "\n",
    "projector_writer = tf.summary.FileWriter(DIR + 'Homework5/projector',sess.graph)\n",
    "saver = tf.train.Saver()\n",
    "config = projector.ProjectorConfig()\n",
    "embed = config.embeddings.add()\n",
    "embed.tensor_name = embedding.name\n",
    "embed.metadata_path = DIR + 'Homework5/projector/metadata.tsv'\n",
    "embed.sprite.image_path = DIR + 'Homework5/data/mnist_10k_sprite.png'\n",
    "embed.sprite.single_image_dim.extend([28,28])\n",
    "projector.visualize_embeddings(projector_writer,config)\n",
    "\n",
    "for i in range(max_steps):\n",
    "    #100 samples for every batch\n",
    "    run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n",
    "    run_metadata = tf.RunMetadata()\n",
    "    batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "    summary,_ = sess.run([merged,train_step],feed_dict={x: batch_xs, y: batch_ys},options=run_options,run_metadata=run_metadata)\n",
    "    projector_writer.add_run_metadata(run_metadata, 'step%03d' % i)\n",
    "    projector_writer.add_summary(summary, i)\n",
    "    \n",
    "    if i%300 == 0:\n",
    "        acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})\n",
    "        print (\"Iter \" + str(i) + \", Testing Accuracy = \" + str(acc))\n",
    "\n",
    "saver.save(sess, DIR + 'Homework5/projector/a_model.ckpt', global_step=max_steps)\n",
    "projector_writer.close\n",
    "sess.close\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
